<template>
  <el-container class="noticeContainer">
    <el-main class="mains">
      <h2>公告发布</h2>
      <el-form
        :model="noticeForm"
        label-position="top"
        :rules="rules"
        ref="noticeForm"
        label-width="100px"
        class="noticeForm"
      >
        <el-form-item label="公告内容" prop="announcementContent">
          <el-input
            type="textarea"
            rows="8"
            :autosize="{ minRows: 8, maxRows: 14 }"
            v-model="noticeForm.announcementContent"
          ></el-input>
        </el-form-item>
        <el-form-item label="公告接收人" required>
          <!-- <el-input type="textarea" rows="8"  :autosize="{ minRows: 8, maxRows: 14}"  v-model="noticeForm.reciver"></el-input> -->
          <div :class="isError ? 'reciverContainer' : 'reciverContainer iserror'">
            <el-row type="flex" class="row-bg" justify="end">
              <el-button type="primary" @click="addReciver" size="mini">添加</el-button>
            </el-row>
            <div class="reciver">
              <div v-if="checkedList.length > 0">
                <el-row :gutter="20">
                  <el-col :span="8"><div class="grid-content bg-purple">产品名称</div></el-col>
                  <el-col :span="16"
                    ><div class="grid-content bg-purple">
                      <el-row :gutter="20">
                        <el-col :span="6"><div class="grid-content bg-purple">OA号</div></el-col>
                        <el-col :span="6"><div class="grid-content bg-purple">姓名</div></el-col>
                        <el-col :span="6"><div class="grid-content bg-purple">部门</div></el-col>
                        <el-col :span="6"><div class="grid-content bg-purple">职位</div></el-col>
                      </el-row>
                    </div></el-col
                  >
                </el-row>
              </div>
              <div v-for="(item, index) in checkedList" :key="index">
                <el-row :gutter="20">
                  <el-col :span="8"
                    ><div class="grid-content bg-purple">{{ item.productName }}</div></el-col
                  >
                  <el-col :span="16"
                    ><div class="grid-content bg-purple">
                      <div v-for="(item1, index1) in item.users" :key="index1">
                        <el-row :gutter="20">
                          <el-col :span="6"
                            ><div class="grid-content bg-purple">{{ item1.userName }}</div></el-col
                          >
                          <el-col :span="6"
                            ><div class="grid-content bg-purple">{{ item1.name }}</div></el-col
                          >
                          <el-col :span="6"
                            ><div class="grid-content bg-purple">{{ item1.department }}</div></el-col
                          >
                          <el-col :span="6"
                            ><div class="grid-content bg-purple">{{ item1.position }}</div></el-col
                          >
                        </el-row>
                      </div>
                    </div></el-col
                  >
                </el-row>
              </div>
              <!-- <p v-for="(item, index) in arrIds" :key="index">
                <span style="width: 60px">{{ item.name }}</span>
                <span style="width: 50px">{{ item.department }}</span>
                <span style="width: 140px">{{ item.position }}</span>
                <span style="width: 140px">{{ item.email }}</span>
              </p> -->
            </div>
          </div>
          <div class="errors" v-if="!isError">请填写公告内容</div>
        </el-form-item>
        <el-form-item>
          <el-row type="flex" class="row-bg" justify="end">
            <el-button @click="resetForm('noticeForm')">重置</el-button>
            <el-button type="primary" @click="submitForm('noticeForm')">发布</el-button>
          </el-row>
        </el-form-item>
      </el-form>
      <el-dialog
        @closed="reciverDialogClose"
        :visible.sync="reciverDialog"
        :close-on-click-modal="false"
        class="reciverDialog"
        title="添加公告接收人"
      >
        <!--   :data="tables" -->
        <!-- <el-table
          height="360"
          ref="reciverTable"
          :data="reciverTableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase())|data.userName.toLowerCase().includes(search.toLowerCase()))"
          :row-key="row => row.id"
          v-loading="reciverTableDataLoading"
          @selection-change="handleSelectionChange"
          tooltip-effect="dark"
        >
          <el-table-column label="C2表" align="right" label-class-name="searchHead">
            <template slot="header">
              <el-input v-model="search" clearable style="width:220px;" size="mini" placeholder="输入关键字搜索" />
            </template>
            <el-table-column type="selection" :reserve-selection="true"> </el-table-column>
            <el-table-column prop="userName" label="OA号"> </el-table-column>
            <el-table-column prop="name" label="姓名"> </el-table-column>
            <el-table-column prop="department" label="部门"> </el-table-column>
            <el-table-column prop="position" label="职位"> </el-table-column>
            <el-table-column prop="email" label="邮箱"> </el-table-column>
          </el-table-column>
        </el-table> -->
        <!-- <el-tree
  :data="ProductSetGetAllList"
  @check-change="handleCheckChange"
  show-checkbox
  default-expand-all
  node-key="id"
  ref="tree"
  highlight-current
  :props="defaultProps">
</el-tree> -->
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0;"></div>
          <el-checkbox v-for="(item, index) in ProductSetGetAllList" :key="index" :label="item">
            <div class="productNameSpan">
              <span @click.prevent="toClickIndex(index)">{{ item.productName }}</span>
            </div>
            <div v-if="item.isClick">
              <li>
                <el-row :gutter="20">
                  <el-col :span="6"><div class="grid-content bg-purple">OA号</div></el-col>
                  <el-col :span="6"><div class="grid-content bg-purple">姓名</div></el-col>
                  <el-col :span="6"><div class="grid-content bg-purple">部门</div></el-col>
                  <el-col :span="6"><div class="grid-content bg-purple">职位</div></el-col>
                </el-row>
                <!-- {{ item1.userName }}-{{item1.name}}-{{ item1.department }}-{{ item1.position }} -->
              </li>
              <li v-for="(item1, index1) in item.users" :key="index1">
                <el-row :gutter="20">
                  <el-col :span="6"
                    ><div class="grid-content bg-purple">{{ item1.userName }}</div></el-col
                  >
                  <el-col :span="6"
                    ><div class="grid-content bg-purple">{{ item1.name }}</div></el-col
                  >
                  <el-col :span="6"
                    ><div class="grid-content bg-purple">{{ item1.department }}</div></el-col
                  >
                  <el-col :span="6"
                    ><div class="grid-content bg-purple">{{ item1.position }}</div></el-col
                  >
                </el-row>
                <!-- {{ item1.userName }}-{{item1.name}}-{{ item1.department }}-{{ item1.position }} -->
              </li>
            </div>
          </el-checkbox>
        </el-checkbox-group>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancleDialog">取消</el-button>
          <el-button type="primary" @click="confirmDialog">确认</el-button>
        </span>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import { notice, Product } from '@/api/setting/service.js'
export default {
    name: 'noticeSetting',
    components: {},
    props: {},
    data() {
        return {
            checkAll: false,
            isIndeterminate: true,
            isError: true,
            noticeForm: {
                userId: '',
                announcementContent: ''
            },
            rules: {
                userId: [
                    {
                        required: true,
                        message: '请填写公告接收人',
                        trigger: 'blur'
                    }
                ],
                announcementContent: [
                    {
                        required: true,
                        message: '请填写公告内容',
                        trigger: 'blur'
                    }
                ]
            },
            clickIndex: '',
            reciverDialog: false,
            // reciverTableData: [],
            search: '',
            // reciverTableDataLoading: false,
            // arrIds: [],
            selecArr: [],
            historyArr: [],
            // 获取的所有产品及人员
            ProductSetGetAllList: [],
            // 多选时选中的产品
            checkedCities: [],
            checkedList: []
        }
    },
    computed: {
    // tables: function() {
    //     const search = this.search
    //     if (search) {
    //         // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
    //         // 注意： filter() 不会对空数组进行检测。
    //         // 注意： filter() 不会改变原始数组。
    //         console.log('434')
    //         // this.historyArr.forEach((element, index) => {
    //         //   this.$refs.reciverTable.toggleRowSelection(element[index]);
    //         // });
    //         return this.reciverTableData.filter(data => {
    //             // some() 方法用于检测数组中的元素是否满足指定条件;
    //             // some() 方法会依次执行数组的每个元素：
    //             // 如果有一个元素满足条件，则表达式返回true , 剩余的元素不会再执行检测;
    //             // 如果没有满足条件的元素，则返回false。
    //             // 注意： some() 不会对空数组进行检测。
    //             // 注意： some() 不会改变原始数组。
    //             return Object.keys(data).some(key => {
    //                 // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
    //                 // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
    //                 return (
    //                     String(data[key])
    //                         .toLowerCase()
    //                         .indexOf(search) > -1
    //                 )
    //             })
    //         })
    //     }
    //     return this.reciverTableData
    // }
    },
    filters: {
        handleNull(v) {
            console.log(v)
            if (v) {
                return v
            } else {
                return '暂无数据'
            }
        }
    },
    watch: {},
    created() {},
    mounted() {
    // this.UserGet()
        this.getCategory()
    },
    methods: {
        toClickIndex(index) {
            this.clickIndex = index
            if (this.ProductSetGetAllList[index].isClick === true) {
                this.ProductSetGetAllList[index].isClick = false
            } else {
                this.ProductSetGetAllList[index].isClick = true
            }
        },
        handleCheckAllChange(val) {
            this.checkedCities = val ? this.ProductSetGetAllList : []
            this.isIndeterminate = false
        },
        handleCheckedCitiesChange(value) {
            // console.log(value)
            // value.splice(0, 1)
            // console.log(value)
            // console.log(this.checkedCities)
            const checkedCount = value.length
            this.checkAll = checkedCount === this.ProductSetGetAllList.length
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.ProductSetGetAllList.length
        },
        // 点击添加按钮
        addReciver() {
            this.reciverDialog = true
            this.checkedCities = this.checkedList
        },
        // 添加页面取消按钮
        cancleDialog() {
            this.reciverDialog = false
            this.checkedCities = []
        },
        // 添加页面确认按钮
        confirmDialog() {
            this.reciverDialog = false
            this.isError = false
            // this.arrIds = this.checkedCities
            const arr2 = []
            // this.arrIds.forEach(element => {
            //     arr2.push(element.id)
            // })
            this.checkedList = this.checkedCities
            for (const item of this.checkedCities) {
                if (item.users != []) {
                    item.users.forEach(element => {
                        arr2.push(element.id)
                    })
                }
            }
            // console.log(arr2)
            const str = arr2
            const str2 = Array.from(new Set(str))
            // console.log(str2)
            this.noticeForm.userId = str2.join(',')
            if (this.noticeForm.userId == '') {
                this.isError = false
            } else {
                this.isError = true
            }
        },
        /**
     * @description: 获取所有数据
     */
        async getCategory() {
            try {
                const result = await Product.ProductSetGetAllListAsync([])
                if (result.success) {
                    // console.log(result.data)
                    const arr = result.data
                    for (const item of arr) {
                        item.isClick = true
                    }
                    this.ProductSetGetAllList = arr
                } else {
                    this.$message.error(result.message)
                }
            } catch (err) {
                this.$message.error('服务器异常')
            }
        },
        submitForm(formName) {
            if (this.noticeForm.userId == '') {
                this.isError = false
            } else {
                this.isError = true
            }
            this.$refs[formName].validate(valid => {
                if (valid && this.isError) {
                    // console.log('成功')
                    this.SendAndSaveAnnouncementAsync(this.noticeForm)
                } else {
                    return false
                }
            })
        },
        reciverDialogClose() {
            this.reciverDialog = false
            // this.search = ''
            // this.$refs.reciverTable.clearSelection()
        },
        handleSelectionChange(val) {
            // console.log(val)
            this.selecArr = val
            //   let arr2 = [];
            //   val.forEach(element => {
            //     arr2.push(element.id);
            //   });
            //   this.noticeForm.userId = arr2.join(',');
        },
        resetForm(formName) {
            this.$refs[formName].resetFields()
            this.isError = true
            this.noticeForm.userId = ''
            this.checkedCities = []
            this.checkedList = []
            // this.$refs.reciverTable.clearSelection()
        },
        // toggleSelection(rows) {
        //     if (rows) {
        //         rows.forEach(row => {
        //             this.$refs.reciverTable.toggleRowSelection(row)
        //         })
        //     } else {
        //         this.$refs.reciverTable.clearSelection()
        //     }
        // },
        // async UserGet() {
        //     try {
        //         const result = await User.UserGetAllUserAsync()
        //         if (result.success) {
        //             console.log(result.data)
        //             // this.reciverTableDataLoading = true;
        //             // setTimeout(() => {
        //             this.reciverTableData = result.data
        //             // this.reciverTableDataLoading = false;
        //             // }, 500);
        //         } else {
        //             this.$message.error(result.message)
        //         }
        //     } catch (err) {
        //         this.$message.error('服务器异常')
        //     }
        // },
        async SendAndSaveAnnouncementAsync(_data) {
            try {
                const result = await notice.SendAndSaveAnnouncementAsync(_data)
                if (result.success) {
                    // console.log(result.data)
                    this.checkedCities = []
                    this.checkedList = []
                    this.$refs.noticeForm.resetFields()
                    this.$message.success(result.message)
                } else {
                    this.$message.error(result.message)
                }
            } catch (err) {
                this.$message.error('服务器异常')
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.noticeContainer {
  background-color: #e6e8eb;
  padding: 30px;
  .mains {
    background: #ffffff;
    border: 1px solid #dcdfe4;
    border-radius: 5px;
    padding: 30px !important;
    .noticeForm {
      margin-top: 20px;
      .reciverContainer {
        padding: 20px;
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        .row-bg {
          margin-bottom: 5px;
        }
        .reciver {
          width: 100%;

          background: #f7f7f7;
          border: 1px solid #dcdfe5;
          border-radius: 5px;
          overflow-y: auto;

          font-size: 14px;

          height: 345px;
          display: block;
          resize: vertical;
          padding: 5px 15px;
          line-height: 1.5;
          box-sizing: border-box;
          width: 100%;
          font-size: inherit;
          color: #606266;
          background: #f7f7f7;
          background-image: none;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
          span {
            margin-left: 7px;
            display: inline-block;
          }
        }
      }
    }
  }
}
::v-deep .el-table thead.is-group .searchHead {
  background: #fff !important;
}
::v-deep .el-dialog {
  margin-top: 10vh !important;
}
::v-deep .reciverDialog .el-dialog__body {
  height: 500px;
  overflow-y: auto;
  overflow-x: hidden;
}
::v-deep .el-checkbox {
  width: 100%;
  position: relative;
}

.iserror {
  border-color: #f56c6c !important;
}
.errors {
  color: #f56c6c;
}
li {
  list-style: none;
  margin-left: 20px;
  width: 100%;
}
::v-deep .el-checkbox__label {
  margin-left: 10px;
  width: 100%;
}
::v-deep .el-checkbox__input {
  position: absolute;
  left: 0;
  top: 0;
}
.productNameSpan {
  font-size: 16px;
}
</style>
